<template>
  <view class="container">
    <!-- 选项卡 -->
    <view class="tab-bar">
      <view class="tab-item" :class="{active:currentTab===0}" @click="currentTab=0">宿舍信息</view>
      <view class="tab-item" :class="{active:currentTab===1}" @click="currentTab=1">缴费信息</view>
      <view class="tab-item" :class="{active:currentTab===2}" @click="currentTab=2">系别信息</view>
    </view>

    <!-- 宿舍信息 -->
    <view class="info-card" v-show="currentTab===0">
      <view class="loading" v-if="dormLoading">
        <u-loading-icon size="40rpx" color="#1e88e5"></u-loading-icon>
        <text class="loading-text">加载中...</text>
      </view>
      <view class="error" v-if="dormError && !dormLoading">
        <u-icon name="error-circle" size="40rpx" color="#f56c6c"></u-icon>
        <text class="error-text">{{ dormErrorMsg }}</text>
        <view class="retry-btn" @click="fetchDormInfo">重试</view>
      </view>
      <!-- 内容 -->
      <view v-if="!dormLoading && !dormError">
          <view class="info-item">
            <text class="label">宿舍ID</text>
            <text class="value">{{ dormInfo.dormitoryId || '-' }}</text>
          </view>
          <view class="info-item">
            <text class="label">宿舍号</text>
            <text class="value">{{ dormInfo.buildingNumber && dormInfo.roomNumber ? `${dormInfo.buildingNumber}-${dormInfo.roomNumber}` : '-' }}</text>
          </view>
          <!-- 宿舍容量信息 -->
          <view class="info-item">
			  <text class="label">可住人数</text>
			  <text class="value">{{ dormInfo.capacity || '-' }}</text>
		  </view>
		  <view class="info-item">
			  <text class="label">当前入住人数</text>
			  <text class="value">{{ dormInfo.currentOccupancy || '-' }}</text>
		  </view>
        </view>
	</view>

    <!-- 缴费信息 -->
    <view class="info-card" v-show="currentTab===1">
      <view class="loading" v-if="paymentLoading">
        <u-loading-icon size="40rpx" color="#1e88e5"></u-loading-icon>
        <text class="loading-text">加载中...</text>
      </view>
      <view class="error" v-if="paymentError && !paymentLoading">
        <u-icon name="error-circle" size="40rpx" color="#f56c6c"></u-icon>
        <text class="error-text">{{ paymentErrorMsg }}</text>
        <view class="retry-btn" @click="fetchPaymentInfo">重试</view>
      </view>
      <view v-if="!paymentLoading && !paymentError">
        <view class="section-header"><text class="title">待缴费用</text></view>
        <view class="fee-section">
          <view class="fee-item" v-for="(item,index) in paymentInfo.feeItems" :key="index">
            <text class="fee-name">{{ item.name }}</text>
            <text class="fee-amount">¥{{ item.amount.toFixed(2) }}</text>
          </view>
          <view class="fee-item total">
            <text class="fee-name">合计</text>
            <text class="fee-amount">¥{{ paymentInfo.totalAmount.toFixed(2) }}</text>
          </view>
        </view> <!-- 修复：添加了这个闭合标签 -->
    
        <!-- 支付方式选择（若未缴费） -->
        <view class="pay-methods" v-if="!paymentInfo.isPaid">
          <text class="pay-methods-header">选择支付方式</text>
          <view class="pay-method" v-for="(method, index) in paymentInfo.payMethods" :key="index"
            @click="selectPayMethod(index)">
            <image class="pay-icon" :src="method.icon"></image>
            <text class="pay-name">{{ method.name }}</text>
            <text class="pay-check" :style="{ color: selectedPayMethod === index ? '#1e88e5' : '#ccc' }">
              {{ selectedPayMethod === index ? '✓' : '' }}
            </text>
          </view>
          <view class="pay-button" @click="handlePayment">
            <text class="pay-btn-text">确认支付</text>
          </view>
        </view>
    
        <!-- 已缴费状态（若已缴费） -->
        <view class="paid-section" v-if="paymentInfo.isPaid">
          <u-icon name="check-circle" size="60rpx" color="#4cd964" class="paid-icon"></u-icon>
          <text class="paid-title">缴费成功</text>
          <text class="paid-desc">
            您已完成{{ paymentInfo.paidTime }}的宿舍费用缴纳，感谢配合！
          </text>
        </view>
      </view>
    </view>

    <!-- 系别信息 -->
    <view class="info-card" v-show="currentTab===2">
      <view class="info-item">
        <text class="label">系别名称</text>
        <text class="value">{{ studentInfo.department || '-' }}</text>
      </view>
      <view class="info-item">
        <text class="label">专业名称</text>
        <text class="value">{{ studentInfo.major || '-' }}</text>
      </view>
      <view class="info-item">
        <text class="label">学生姓名</text>
        <text class="value">{{ studentInfo.name || '-' }}</text>
      </view>
      <view class="info-item">
        <text class="label">学号</text>
        <text class="value">{{ studentInfo.studentNumber || '-' }}</text>
      </view>
      <view class="info-item">
        <text class="label">年龄</text>
        <text class="value">{{ studentInfo.age || '-' }}</text>
      </view>
      <view class="info-item">
        <text class="label">性别</text>
        <text class="value">{{ studentInfo.gender || '-' }}</text>
      </view>
      <view class="info-item">
        <text class="label">入学日期</text>
        <text class="value">{{ studentInfo.enrollmentDate || '-' }}</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      currentTab: 0,
      studentInfo: {},
      dormInfo: {},
      dormLoading: false,
      dormError: false,
      dormErrorMsg: '',
      paymentLoading: false,
      paymentError: false,
      paymentErrorMsg: '',
      paymentInfo: {
        feeItems: [],
        totalAmount: 0,
        isPaid: false,
        paidTime: '',
        payMethods: [
          { name: '微信', icon: '/static/image/image/wechat.png' },
          { name: '支付宝',   icon: '/static/image/image/alipay.png' },
          { name: '银行卡',   icon: '/static/image/image/unionpay.png' }
        ]
      },
      selectedPayMethod: 0
    };
  },

  computed: {
    dormCapacity()       { return this.dormInfo.capacity ?? 0; },
    dormCurrentOccupancy() { return this.dormInfo.currentOccupancy ?? 0; }
  },

  onShow() {
    console.log('==== onShow 触发 ====');
    const sn = uni.getStorageSync('studentNumber');
    console.log('缓存中学号：', sn);
    if (!sn) {
      console.log('没取到学号，跳登录');
      uni.navigateTo({ url: '/pages/login/index' });
      return;
    }
    this.studentInfo = uni.getStorageSync('studentInfo') || {};
    console.log('已赋值 studentInfo:', this.studentInfo);
    this.loadCurrentTabData();
  },

  methods: {
    loadCurrentTabData() {
      const map = [this.fetchDormInfo, this.fetchPaymentInfo, () => {}];
      map[this.currentTab]();
    },

    /* 宿舍信息 - 无改动 */
    async fetchDormInfo() {
      this.dormLoading = true;
      this.dormError   = false;
      this.dormInfo    = {};
      try {
        const dormitoryId = this.studentInfo.dormitoryId;
        console.log('从学生信息获取的dormitoryId:', dormitoryId);
        if (!dormitoryId || dormitoryId <= 0) throw new Error('未分配宿舍');

        uni.request({
          url: `http://localhost:8080/dormitory/getDormitoryById/${dormitoryId}`,
          method: 'GET',
          success: (res) => {
            if (res.statusCode === 200 && res.data.code === 200) {
              this.dormInfo = res.data.data || {};
              uni.setStorageSync('dormitoryId', dormitoryId);
            } else throw new Error(res.data.message || '获取宿舍信息失败');
          },
          fail: (err) => { throw new Error(`网络请求失败: ${err.errMsg}`); },
          complete: () => { this.dormLoading = false; }
        });
      } catch (e) {
        this.dormError    = true;
        this.dormErrorMsg = e.message || '网络错误，请稍后重试';
        console.error('请求异常:', e);
        this.dormLoading  = false;
      }
    },

    /* 缴费信息 - 只改判断逻辑 */
    async fetchPaymentInfo() {
      console.log('==== fetchPaymentInfo ====');
      this.paymentLoading = true;
      this.paymentError   = false;
      try {
        const studentNumber = uni.getStorageSync('studentNumber');
        if (!studentNumber) throw new Error('未获取到学生信息，请重新登录');

        /* 1. 查询学生已缴记录 */
        const recordRes = await new Promise((resolve, reject) => {
          uni.request({
            url: 'http://localhost:8080/api/paymentRecord/studentNumber',
            method: 'GET',
            data: { studentNumber, currentPage: 1, pageSize: 100 },
            success: resolve,
            fail: reject
          });
        });

        /* 2. 查询系统全部缴费项目 */
        const allItemsRes = await new Promise((resolve, reject) => {
          uni.request({
            url: 'http://localhost:8080/api/payment',
            method: 'GET',
            data: { currentPage: 1, pageSize: 100 },
            success: resolve,
            fail: reject
          });
        });

        /* 3. 判断返回是否成功 - 修复点 */
        if (recordRes.statusCode !== 200 || recordRes.data.code !== 200) {
          throw new Error(recordRes.data.message || '获取缴费记录失败，请稍后重试');
        }
        if (allItemsRes.statusCode !== 200 || allItemsRes.data.code !== 200) {
          throw new Error(allItemsRes.data.message || '获取缴费项目列表失败，请稍后重试');
        }

        /* 4. 解析数据 */
        const paidRecords     = recordRes.data.data.list || [];
        const allPaymentItems = allItemsRes.data.data.list || [];

        const paidItemNames = paidRecords
          .filter(r => r.status === '已支付')
          .map(r => r.itemName);

        const unpaidItems = allPaymentItems
          .filter(i => !paidItemNames.includes(i.itemName))
          .map(i => ({ name: i.itemName, amount: Number(i.amount) }));

        const totalUnpaidAmount = unpaidItems.reduce((s, i) => s + i.amount, 0);

        let isAllPaid    = unpaidItems.length === 0;
        let latestPaidTime = '';
        if (isAllPaid && paidRecords.length > 0) {
          const latest = paidRecords.sort((a, b) => new Date(b.paymentDate) - new Date(a.paymentDate))[0];
          latestPaidTime = new Date(latest.paymentDate).toLocaleDateString();
        }

        this.paymentInfo = {
          feeItems: unpaidItems,
          totalAmount: totalUnpaidAmount,
          isPaid: isAllPaid,
          paidTime: latestPaidTime,
          payMethods: this.paymentInfo.payMethods
        };
      } catch (e) {
        this.paymentError    = true;
        this.paymentErrorMsg = e.message || '获取缴费信息失败，请检查网络后重试';
        console.error('缴费信息请求异常:', e);
      } finally {
        this.paymentLoading  = false;
      }
    },

    selectPayMethod(index) {
      this.selectedPayMethod = index;
    },

   async handlePayment() {
     const methodName = this.paymentInfo.payMethods[this.selectedPayMethod].name;
     uni.showLoading({ title: '支付中...' });
   
     try {
       const res = await new Promise((resolve, reject) => {
         uni.request({
           url: 'http://localhost:8080/api/paymentRecord/payAll',
           method: 'POST',
           header: { 'Content-Type': 'application/json' },
           data: {
             studentNumber: uni.getStorageSync('studentNumber'),
             paymentMethod: methodName
           },
           success: resolve,
           fail: reject
         });
       });
   
       if (res.statusCode !== 200 || res.data.code !== 200) {
         throw new Error(res.data.message || '支付失败');
       }
   
       // 1. 前端立刻切换已缴费状态
       this.paymentInfo.isPaid = true;
       this.paymentInfo.paidTime = new Date().toLocaleDateString();
       this.paymentInfo.feeItems = [];
       this.paymentInfo.totalAmount = 0;
   
       uni.hideLoading();
       uni.showToast({ title: '支付完成', icon: 'success' });
	   
   
        // ✅ 关键：重新拉取缴费数据
       this.fetchPaymentInfo(); // 或你之前封装的加载方法
     } catch (e) {
       uni.hideLoading();
       uni.showToast({ title: e.message || '支付失败', icon: 'none' });
     }
   }
  }
};
</script>
</script>

<style scoped>
.container {
	padding: 20rpx;
}

.tab-bar {
	display: flex;
	border-bottom: 1rpx solid #eee;
	margin-bottom: 20rpx;
}

.tab-item {
	flex: 1;
	text-align: center;
	padding: 20rpx 0;
	font-size: 30rpx;
	color: #666;
}

.tab-item.active {
	color: #1e88e5;
	border-bottom: 4rpx solid #1e88e5;
	font-weight: bold;
}

.info-card {
	background-color: #fff;
	border-radius: 20rpx;
	padding: 25rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

/* 其他样式保持不变 */
.section-header {
	padding: 10rpx 0 20rpx 0;
	border-bottom: 1rpx solid #f5f5f5;
	margin-bottom: 20rpx;
}

.title {
	font-size: 32rpx;
	font-weight: bold;
}

.loading, .error {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 60rpx 0;
}

.loading-text, .error-text {
	font-size: 28rpx;
	color: #666;
	margin-top: 20rpx;
}

.retry-btn {
	margin-top: 20rpx;
	padding: 10rpx 30rpx;
	background-color: #1e88e5;
	color: #fff;
	border-radius: 8rpx;
	font-size: 26rpx;
}

.fee-section {
	width: 100%;
}

.fee-header, .pay-methods-header {
	font-size: 28rpx;
	color: #666;
	margin-bottom: 15rpx;
}

.fee-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 15rpx 0;
	border-bottom: 1rpx solid #f5f5f5;
}

.fee-item:last-child {
	border-bottom: none;
}

.fee-name {
	font-size: 28rpx;
	color: #333;
}

.fee-amount {
	font-size: 28rpx;
	color: #333;
}

.fee-item.total {
	font-weight: bold;
	margin-top: 10rpx;
}

.pay-methods {
	margin-top: 30rpx;
}

.pay-method {
	display: flex;
	align-items: center;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #f5f5f5;
}

.pay-method:last-child {
	border-bottom: none;
}

.pay-icon {
	width: 40rpx;
	height: 40rpx;
	margin-right: 15rpx;
}

.pay-name {
	font-size: 28rpx;
	color: #333;
	flex: 1;
}

.pay-check {
	font-size: 36rpx;
}

.pay-button {
	margin-top: 40rpx;
	background-color: #2196F3;
	border-radius: 8rpx;
	padding: 20rpx 0;
	text-align: center;
}

.pay-btn-text {
	color: #fff;
	font-size: 32rpx;
	font-weight: bold;
}

.paid-section {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 60rpx 0;
}

.paid-icon {
	margin-bottom: 20rpx;
}

.paid-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 10rpx;
}

.paid-desc {
	font-size: 28rpx;
	color: #666;
	text-align: center;
	width: 80%;
}

.info-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #f5f5f5;
}

.info-item:last-child {
	border-bottom: none;
}

.label {
	font-size: 28rpx;
	color: #666;
	width: 160rpx;
}

.value {
	font-size: 28rpx;
	color: #333;
	word-break: break-all;
	flex: 1;
	text-align: right;
}
</style>
